package cn.tedu.mall.order.controller;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.JsonResult;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.order.service.IOmsOrderService;
import cn.tedu.mall.pojo.order.dto.OrderAddDTO;
import cn.tedu.mall.pojo.order.dto.OrderListTimeDTO;
import cn.tedu.mall.pojo.order.vo.OrderAddVO;
import cn.tedu.mall.pojo.order.vo.OrderListVO;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class OrderController {
    /**
     * 新增订单,
     * 1.发送异步消息
     */
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @PostMapping("/oms/order/add")
    @PreAuthorize("hasRole('ROLE_user')")
    public JsonResult<OrderAddVO> addOrder(OrderAddDTO orderAddDTO) {
        //生成一个SN，并转化为String类型
        String sn = UUID.randomUUID().toString();
        orderAddDTO.setSn(sn);//为orderAddDTO设置sn
        //发送消息
        String msg = JSON.toJSONString(orderAddDTO);
        //将消息发送到主题,并且绑定一个标签tag=localAdd 后面还有秒杀消息tag=seckillAdd
        SendResult sendResult = rocketMQTemplate.
                syncSend("csmall-order-add-topic:localAdd", msg);
        if (sendResult.getSendStatus().toString().equals("SEND_OK")) {
            //返回成功
            OrderAddVO orderAddVO = new OrderAddVO();
            orderAddVO.setSn(sn);
            //UNDO 如果有计价中心,金额应该是远程调用计价中心反馈的
            //为orderAddVO设置需要支付的金额
            orderAddVO.setPayAmount(orderAddDTO.getAmountOfActualPay());
            return JsonResult.ok(orderAddVO);
        } else {
            throw new CoolSharkServiceException(
                    ResponseCode.BAD_REQUEST, "新增失败");
        }
    }
    /*@GetMapping("/oms/order/sn/create")
    @PreAuthorize("hasRole('ROLE_user')")
    public JsonResult<String> createSN(){
        //生成sn 如果只考虑唯一性,sn很容易的,如果又考虑唯一性,又考虑业务数据
        //不太好生成,如果还要考虑极高并发 1秒中10亿次,极难.
        String sn="1";
        return JsonResult.ok(sn);
    }*/

    @Autowired
    private IOmsOrderService omsOrderService;

    /**
     * 查询我的订单数据
     */
    @GetMapping("/oms/order/list")
    @PreAuthorize("hasRole('ROLE_user')")
    public JsonResult<JsonPage<OrderListVO>> listTimeOrders(OrderListTimeDTO orderListTimeDTO) {
        JsonPage<OrderListVO> orderListVOJsonPage =
                omsOrderService.listOrdersBetweenTimes(orderListTimeDTO);
        return JsonResult.ok(orderListVOJsonPage);
    }
}
